package com.ruoyi.web.controller.wa;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BulkMessage;
import com.ruoyi.system.domain.BulkSendName;
import com.ruoyi.system.domain.CustomerInfo;
import com.ruoyi.system.domain.CustomerChat;
import com.ruoyi.system.service.IWaClientService;
import com.ruoyi.system.service.ICustomerInfoService;
import com.ruoyi.system.service.impl.StatusCheckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/wa/client")
public class WaClientController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WaClientController.class);


    @Autowired
    private Environment env;

    @Autowired
    private IWaClientService customerChatService;

    @Autowired
    private ICustomerInfoService cusUserService;

    @Autowired
    private StatusCheckService statusCheckService;


    @Value("${apiSevicePath.newChat}")
    private String newChatURL;

    @Value("${devicesPath.clinetBluk}")
    private String clinetBluk;

    @Value("${devicesPath.syncBook}")
    private String syncBook;



    @PreAuthorize("@ss.hasPermi('client:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustomerChat customerChat) {
        startPage();
//        LoginUser loginUser = getLoginUser();
//        SysUser sysUser =loginUser.getUser();
//        if (sysUser.getUserName().equals("A001")){
//            customerChat.setTemplateId("103");
//        }
        List<CustomerChat> list = customerChatService.selectChatList(customerChat);
        return getDataTable(list);
    }

    @Log(title = "客服管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('client:user:edit')")
    @PutMapping()
    public AjaxResult edit(@Validated @RequestBody CustomerChat customerChat) {
        CustomerInfo cusUser = cusUserService.selectUserByNumber(customerChat.getCustomerNumber());
        if (StringUtils.isNull(cusUser)){
            return error("客服不存在");
        }
        customerChat.setUserId(cusUser.getUserId());
        customerChat.setDeptId(cusUser.getDeptId());
        return toAjax(customerChatService.updateCustomerChat(customerChat));
    }

    @PreAuthorize("@ss.hasPermi('client:user:edit')")
    @GetMapping(value = "/{id}")
    public AjaxResult getCustomer(@PathVariable String id) {
        return success(customerChatService.selectChatById(id));
    }

    /**
     * 新增粉丝
     */
    @PreAuthorize("@ss.hasPermi('client:user:add')")
    @Log(title = "粉丝管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CustomerChat user) {
        if (StringUtils.isEmpty(user.getCustomerNumber())) {
            return error("粉丝专属坐席号码不能为空");
        }
        CustomerChat chatU = customerChatService.selectChatByClientNumber(user.getClientNumber());
        if (StringUtils.isNotNull(chatU)){
            return error("粉丝号码已存在");
        }
        CustomerInfo cusUser = cusUserService.selectUserByNumber(user.getCustomerNumber());
        if (StringUtils.isNull(cusUser)){
            return error("客服不存在");
        }
        user.setUserId(cusUser.getUserId());
        user.setDeptId(cusUser.getDeptId());
        return toAjax(customerChatService.insertUser(user));
    }

    @PreAuthorize("@ss.hasPermi('client:user:bulk')")
    @Log(title = "群发", businessType = BusinessType.INSERT)
    @PostMapping("/bulk")
    public AjaxResult bulk(@Validated @RequestBody BulkMessage bulkMessage) {
        if (StringUtils.isNull(bulkMessage)) {
            return error("群发内容为空");
        }
        if (StringUtils.isNull(bulkMessage.getIds())){
            return error("粉丝账户不存在");
        }

        int status = customerChatService.bulkMessage(bulkMessage);

        return success(status);
    }

    /**
     * 删除坐席
     */
    @PreAuthorize("@ss.hasPermi('client:user:remove')")
    @Log(title = "坐席管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String[] id) {
        return toAjax(customerChatService.deleteUserByNumbers(id));
    }

    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('client:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CustomerChat> util = new ExcelUtil<CustomerChat>(CustomerChat.class);
        List<CustomerChat> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = customerChatService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('client:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerChat user) {
        List<CustomerChat> list = customerChatService.selectChatList(user);
        ExcelUtil<CustomerChat> util = new ExcelUtil<CustomerChat>(CustomerChat.class);
        util.exportExcel(response, list, "whatsapp数据");
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CustomerChat> util = new ExcelUtil<CustomerChat>(CustomerChat.class);
        util.importTemplateExcel(response, "whatsapp数据");
    }

    @PreAuthorize("@ss.hasPermi('client:user:init')")
    @GetMapping("/clientInit")
    public AjaxResult clientInit() {
        log.info("----------------  autoChat  autoChat-------------------");
        String rspStr = HttpUtils.sendGet(env.getProperty("apiSevicePath.autoChat"));
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/clientChat/{id}")
    public AjaxResult clientChat(@PathVariable("id") String id) {
        log.info("----------------  autoChat  newChat-------------------:"+newChatURL);
        String rspStr = HttpUtils.sendGet(newChatURL + id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }


    /**
     * 获取登录二维码
     */
    @PreAuthorize("@ss.hasPermi('customer:user:auto')")
    @GetMapping("/autoChat/{id}")
    public AjaxResult createClient(@PathVariable("id") String id) {
        String rspStr = HttpUtils.sendGet(env.getProperty("apiSevicePath.auto_Chat") + id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/clinetBluk")
    public AjaxResult clinetBluk(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  clinetBluk-------------------:" + clinetBluk);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids + "&";
        // 对message进行URL编码
        String encodedMessage = URLEncoder.encode(bulkSendName.getMessage(), StandardCharsets.UTF_8.toString());
        param += "message=" + encodedMessage;
        String rspStr = HttpUtils.sendGet(clinetBluk + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:syncBook')")
    @PostMapping("/syncBook")
    public AjaxResult syncBook(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  syncBook-------------------:" + syncBook);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String rspStr = HttpUtils.sendGet(syncBook + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

}
